/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 2009 - 2012 Luca Mingardi.
 *
 * This file is part of jeeObserver.
 *
 * JeeObserver is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * JeeObserver is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */
package jeeobserver.server.database;

import java.util.Date;
import java.util.TimerTask;
import java.util.logging.Level;
import jeeobserver.server.ActionParameters;
import jeeobserver.server.HardDiskParameters;
import jeeobserver.server.HardDiskParameters;
import jeeobserver.server.HttpSessionParameters;
import jeeobserver.server.HttpSessionParameters;
import jeeobserver.server.JeeObserverServerContext;
import jeeobserver.server.JeeObserverServerContext;
import jeeobserver.server.JvmParameters;
import jeeobserver.server.JvmParameters;
import jeeobserver.settings.Settings;
import jeeobserver.settings.TimeSchedule;

/**
 * The Class DatabaseHandlerTimerTask.
 *
 * @author Luca Mingardi
 * @version 4.0
 */
final class DatabaseHandlerTimerTask extends TimerTask {

	/** The Constant TIMER_INTERVAL. */
	public static final long TIMER_INTERVAL = 30 * 1000;// 30 Seconds

	private static Date lastTablesOptimizationDate = null;

	private static Date lastTablesCleanDate = null;

	@Override
	public void run() {

		if (!JeeObserverServerContext.getInstance().isEnabled()) {
			return;
		}

		Settings settings;

		try {
			settings = JeeObserverServerContext.getInstance().getDatabaseHandler().loadSettings();
		} catch (final Exception e) {
			JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage(), e);
			return;
		}

		final Date currentDate = new Date();

		final TimeSchedule cleanTimeSchedule = settings.getTablesCleanSchedule();

		if ((cleanTimeSchedule != null) && cleanTimeSchedule.isDateIntoSchedule(currentDate, DatabaseHandlerTimerTask.lastTablesCleanDate)) {

			DatabaseHandlerTimerTask.lastTablesCleanDate = new Date();

			JeeObserverServerContext.logger.log(Level.FINE, "Cleaning database.");

			// Clear actions
			Date date = settings.getActionMaxStoragePeriod().subtractToDate(new Date());

			JeeObserverServerContext.logger.log(Level.FINE, "Cleaning actions database. Deleting before {0}", date);

			try {
				JeeObserverServerContext.getInstance().getDatabaseHandler().deleteActionStatistics(new ActionParameters.DeleteStatisticsParameter(null, date));
			} catch (final DatabaseException e) {
				JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage(), e);
			}

			// Clear JVM
			date = settings.getJvmMaxStoragePeriod().subtractToDate(new Date());

			JeeObserverServerContext.logger.log(Level.FINE, "Cleaning JVM database. Deleting before {0}", date);

			try {
				JeeObserverServerContext.getInstance().getDatabaseHandler().deleteJvmStatistics(new JvmParameters.DeleteStatisticsParameter(null, date));
			} catch (final DatabaseException e) {
				JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage(), e);
			}

			// Clear HTTP Sessions
			date = settings.getHttpSessionMaxStoragePeriod().subtractToDate(new Date());

			JeeObserverServerContext.logger.log(Level.FINE, "Cleaning HTTP sessions database. Deleting before {0}", date);

			try {
				JeeObserverServerContext.getInstance().getDatabaseHandler().deleteHttpSessionStatistics(new HttpSessionParameters.DeleteStatisticsParameter(null, date));
			} catch (final DatabaseException e) {
				JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage(), e);
			}

			// Clear Hard Disk
			date = settings.getHardDiskMaxStoragePeriod().subtractToDate(new Date());

			JeeObserverServerContext.logger.log(Level.FINE, "Cleaning Hard Disk database. Deleting before {0}", date);

			try {
				JeeObserverServerContext.getInstance().getDatabaseHandler().deleteHardDiskStatistics(new HardDiskParameters.DeleteStatisticsParameter(null, date));
			} catch (final DatabaseException e) {
				JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage(), e);
			}
		}

		// Optimize database tables and indexes
		final TimeSchedule optimizationTimeSchedule = settings.getTablesOptimizationSchedule();

		if ((optimizationTimeSchedule != null) && optimizationTimeSchedule.isDateIntoSchedule(currentDate, DatabaseHandlerTimerTask.lastTablesOptimizationDate)) {

			DatabaseHandlerTimerTask.lastTablesOptimizationDate = new Date();

			JeeObserverServerContext.logger.log(Level.FINE, "Optimize free space from database");

			//TODO
			/*try {
				JeeObserverServerContext.getInstance().getDatabaseHandler().optimizeDatabase();
			} catch (final DatabaseException e) {
				JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage(), e);
			}*/
		}
	}
}
